<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlpacktut - tutorial on pack and unpack - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlpacktut">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlpacktut.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlpacktut">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlpacktut">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlpacktut">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlpacktut">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlpacktut">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlpacktut">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlpacktut">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlpacktut">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlpacktut">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlpacktut">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlpacktut">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlpacktut">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlpacktut">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlpacktut">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlpacktut">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlpacktut">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlpacktut">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlpacktut">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlpacktut">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlpacktut">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlpacktut">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlpacktut">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlpacktut">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlpacktut">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlpacktut">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlpacktut">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlpacktut">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlpacktut">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlpacktut">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlpacktut">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlpacktut">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlpacktut">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlpacktut">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlpacktut">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlpacktut">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlpacktut">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlpacktut">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlpacktut">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlpacktut">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlpacktut">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlpacktut">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlpacktut">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlpacktut">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlpacktut">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlpacktut">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlpacktut">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlpacktut">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlpacktut">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlpacktut">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlpacktut">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlpacktut">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlpacktut">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlpacktut">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlpacktut">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlpacktut">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlpacktut">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlpacktut">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlpacktut">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlpacktut">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlpacktut">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlpacktut">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlpacktut">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlpacktut">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlpacktut">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlpacktut">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlpacktut">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlpacktut">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlpacktut">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlpacktut">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlpacktut">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlpacktut">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlpacktut">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlpacktut">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlpacktut">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlpacktut">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlpacktut">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlpacktut">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlpacktut">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlpacktut">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlpacktut">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlpacktut.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlpacktut">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlpacktut">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlpacktut">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlpacktut">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlpacktut">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlpacktut">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlpacktut">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlpacktut">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlpacktut">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlpacktut">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlpacktut">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlpacktut">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlpacktut">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlpacktut">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlpacktut">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlpacktut">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlpacktut">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlpacktut">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlpacktut">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlpacktut">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlpacktut">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlpacktut">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlpacktut">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlpacktut">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlpacktut">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlpacktut">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlpacktut">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlpacktut">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlpacktut">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlpacktut">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlpacktut">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlpacktut">5.35.1</a>
          <a class="dropdown-item active" href="perlpacktut.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlpacktut.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlpacktut.html">perlpacktut</a>
          <div id="more">
            (<a href="perlpacktut.txt">source</a>,
            <a href="https://metacpan.org/pod/perlpacktut">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#The-Basic-Principle">The Basic Principle</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Packing-Text">Packing Text</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Packing-Numbers">Packing Numbers</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Integers">Integers</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Unpacking-a-Stack-Frame">Unpacking a Stack Frame</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#How-to-Eat-an-Egg-on-a-Net">How to Eat an Egg on a Net</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Byte-order-modifiers">Byte-order modifiers</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Floating-point-Numbers">Floating point Numbers</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Exotic-Templates">Exotic Templates</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Bit-Strings">Bit Strings</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Uuencoding">Uuencoding</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Doing-Sums">Doing Sums</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Unicode">Unicode</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Another-Portable-Binary-Encoding">Another Portable Binary Encoding</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Template-Grouping">Template Grouping</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Lengths-and-Widths">Lengths and Widths</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#String-Lengths">String Lengths</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Dynamic-Templates">Dynamic Templates</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Counting-Repetitions">Counting Repetitions</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Intel-HEX">Intel HEX</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Packing-and-Unpacking-C-Structures">Packing and Unpacking C Structures</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#The-Alignment-Pit">The Alignment Pit</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Dealing-with-Endian-ness">Dealing with Endian-ness</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Alignment,-Take-2">Alignment, Take 2</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Alignment,-Take-3">Alignment, Take 3</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Pointers-for-How-to-Use-Them">Pointers for How to Use Them</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Pack-Recipes">Pack Recipes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Funnies-Section">Funnies Section</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlpacktut.html#Authors">Authors</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlpacktut.html#NAME">#</a>NAME</h1>

<p>perlpacktut - tutorial on <code>pack</code> and <code>unpack</code></p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlpacktut.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p><code>pack</code> and <code>unpack</code> are two functions for transforming data according to a user-defined template, between the guarded way Perl stores values and some well-defined representation as might be required in the environment of a Perl program. Unfortunately, they&#39;re also two of the most misunderstood and most often overlooked functions that Perl provides. This tutorial will demystify them for you.</p>

<h1 id="The-Basic-Principle"><a class="permalink" href="perlpacktut.html#The-Basic-Principle">#</a><a id="The"></a>The Basic Principle</h1>

<p>Most programming languages don&#39;t shelter the memory where variables are stored. In C, for instance, you can take the address of some variable, and the <code>sizeof</code> operator tells you how many bytes are allocated to the variable. Using the address and the size, you may access the storage to your heart&#39;s content.</p>

<p>In Perl, you just can&#39;t access memory at random, but the structural and representational conversion provided by <code>pack</code> and <code>unpack</code> is an excellent alternative. The <code>pack</code> function converts values to a byte sequence containing representations according to a given specification, the so-called &quot;template&quot; argument. <code>unpack</code> is the reverse process, deriving some values from the contents of a string of bytes. (Be cautioned, however, that not all that has been packed together can be neatly unpacked - a very common experience as seasoned travellers are likely to confirm.)</p>

<p>Why, you may ask, would you need a chunk of memory containing some values in binary representation? One good reason is input and output accessing some file, a device, or a network connection, whereby this binary representation is either forced on you or will give you some benefit in processing. Another cause is passing data to some system call that is not available as a Perl function: <code>syscall</code> requires you to provide parameters stored in the way it happens in a C program. Even text processing (as shown in the next section) may be simplified with judicious usage of these two functions.</p>

<p>To see how (un)packing works, we&#39;ll start with a simple template code where the conversion is in low gear: between the contents of a byte sequence and a string of hexadecimal digits. Let&#39;s use <code>unpack</code>, since this is likely to remind you of a dump program, or some desperate last message unfortunate programs are wont to throw at you before they expire into the wild blue yonder. Assuming that the variable <code>$mem</code> holds a sequence of bytes that we&#39;d like to inspect without assuming anything about its meaning, we can write</p>

<pre><code>my( $hex ) = unpack( &#39;H*&#39;, $mem );
print &quot;$hex\n&quot;;</code></pre>

<p>whereupon we might see something like this, with each pair of hex digits corresponding to a byte:</p>

<pre><code class="plaintext">41204d414e204120504c414e20412043414e414c2050414e414d41</code></pre>

<p>What was in this chunk of memory? Numbers, characters, or a mixture of both? Assuming that we&#39;re on a computer where ASCII (or some similar) encoding is used: hexadecimal values in the range <code>0x40</code> - <code>0x5A</code> indicate an uppercase letter, and <code>0x20</code> encodes a space. So we might assume it is a piece of text, which some are able to read like a tabloid; but others will have to get hold of an ASCII table and relive that firstgrader feeling. Not caring too much about which way to read this, we note that <code>unpack</code> with the template code <code>H</code> converts the contents of a sequence of bytes into the customary hexadecimal notation. Since &quot;a sequence of&quot; is a pretty vague indication of quantity, <code>H</code> has been defined to convert just a single hexadecimal digit unless it is followed by a repeat count. An asterisk for the repeat count means to use whatever remains.</p>

<p>The inverse operation - packing byte contents from a string of hexadecimal digits - is just as easily written. For instance:</p>

<pre><code>my $s = pack( &#39;H2&#39; x 10, 30..39 );
print &quot;$s\n&quot;;</code></pre>

<p>Since we feed a list of ten 2-digit hexadecimal strings to <code>pack</code>, the pack template should contain ten pack codes. If this is run on a computer with ASCII character coding, it will print <code>0123456789</code>.</p>

<h1 id="Packing-Text"><a class="permalink" href="perlpacktut.html#Packing-Text">#</a><a id="Packing"></a>Packing Text</h1>

<p>Let&#39;s suppose you&#39;ve got to read in a data file like this:</p>

<pre><code class="plaintext">Date      |Description                | Income|Expenditure
01/24/2001 Zed&#39;s Camel Emporium                    1147.99
01/28/2001 Flea spray                                24.99
01/29/2001 Camel rides to tourists      235.00</code></pre>

<p>How do we do it? You might think first to use <code>split</code>; however, since <code>split</code> collapses blank fields, you&#39;ll never know whether a record was income or expenditure. Oops. Well, you could always use <code>substr</code>:</p>

<pre><code>while (&lt;&gt;) { 
    my $date   = substr($_,  0, 11);
    my $desc   = substr($_, 12, 27);
    my $income = substr($_, 40,  7);
    my $expend = substr($_, 52,  7);
    ...
}</code></pre>

<p>It&#39;s not really a barrel of laughs, is it? In fact, it&#39;s worse than it may seem; the eagle-eyed may notice that the first field should only be 10 characters wide, and the error has propagated right through the other numbers - which we&#39;ve had to count by hand. So it&#39;s error-prone as well as horribly unfriendly.</p>

<p>Or maybe we could use regular expressions:</p>

<pre><code>while (&lt;&gt;) { 
    my($date, $desc, $income, $expend) = 
        m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
    ...
}</code></pre>

<p>Urgh. Well, it&#39;s a bit better, but - well, would you want to maintain that?</p>

<p>Hey, isn&#39;t Perl supposed to make this sort of thing easy? Well, it does, if you use the right tools. <code>pack</code> and <code>unpack</code> are designed to help you out when dealing with fixed-width data like the above. Let&#39;s have a look at a solution with <code>unpack</code>:</p>

<pre><code>while (&lt;&gt;) { 
    my($date, $desc, $income, $expend) = unpack(&quot;A10xA27xA7A*&quot;, $_);
    ...
}</code></pre>

<p>That looks a bit nicer; but we&#39;ve got to take apart that weird template. Where did I pull that out of?</p>

<p>OK, let&#39;s have a look at some of our data again; in fact, we&#39;ll include the headers, and a handy ruler so we can keep track of where we are.</p>

<pre><code class="plaintext">         1         2         3         4         5        
1234567890123456789012345678901234567890123456789012345678
Date      |Description                | Income|Expenditure
01/28/2001 Flea spray                                24.99
01/29/2001 Camel rides to tourists      235.00</code></pre>

<p>From this, we can see that the date column stretches from column 1 to column 10 - ten characters wide. The <code>pack</code>-ese for &quot;character&quot; is <code>A</code>, and ten of them are <code>A10</code>. So if we just wanted to extract the dates, we could say this:</p>

<pre><code>my($date) = unpack(&quot;A10&quot;, $_);</code></pre>

<p>OK, what&#39;s next? Between the date and the description is a blank column; we want to skip over that. The <code>x</code> template means &quot;skip forward&quot;, so we want one of those. Next, we have another batch of characters, from 12 to 38. That&#39;s 27 more characters, hence <code>A27</code>. (Don&#39;t make the fencepost error - there are 27 characters between 12 and 38, not 26. Count &#39;em!)</p>

<p>Now we skip another character and pick up the next 7 characters:</p>

<pre><code>my($date,$description,$income) = unpack(&quot;A10xA27xA7&quot;, $_);</code></pre>

<p>Now comes the clever bit. Lines in our ledger which are just income and not expenditure might end at column 46. Hence, we don&#39;t want to tell our <code>unpack</code> pattern that we <b>need</b> to find another 12 characters; we&#39;ll just say &quot;if there&#39;s anything left, take it&quot;. As you might guess from regular expressions, that&#39;s what the <code>*</code> means: &quot;use everything remaining&quot;.</p>

<ul>

<li><p>Be warned, though, that unlike regular expressions, if the <code>unpack</code> template doesn&#39;t match the incoming data, Perl will scream and die.</p>

</li>
</ul>

<p>Hence, putting it all together:</p>

<pre><code>my ($date, $description, $income, $expend) =
    unpack(&quot;A10xA27xA7xA*&quot;, $_);</code></pre>

<p>Now, that&#39;s our data parsed. I suppose what we might want to do now is total up our income and expenditure, and add another line to the end of our ledger - in the same format - saying how much we&#39;ve brought in and how much we&#39;ve spent:</p>

<pre><code>while (&lt;&gt;) {
    my ($date, $desc, $income, $expend) =
        unpack(&quot;A10xA27xA7xA*&quot;, $_);
    $tot_income += $income;
    $tot_expend += $expend;
}

$tot_income = sprintf(&quot;%.2f&quot;, $tot_income); # Get them into 
$tot_expend = sprintf(&quot;%.2f&quot;, $tot_expend); # &quot;financial&quot; format

$date = POSIX::strftime(&quot;%m/%d/%Y&quot;, localtime); 

# OK, let&#39;s go:

print pack(&quot;A10xA27xA7xA*&quot;, $date, &quot;Totals&quot;,
    $tot_income, $tot_expend);</code></pre>

<p>Oh, hmm. That didn&#39;t quite work. Let&#39;s see what happened:</p>

<pre><code class="plaintext">01/24/2001 Zed&#39;s Camel Emporium                     1147.99
01/28/2001 Flea spray                                 24.99
01/29/2001 Camel rides to tourists     1235.00
03/23/2001Totals                     1235.001172.98</code></pre>

<p>OK, it&#39;s a start, but what happened to the spaces? We put <code>x</code>, didn&#39;t we? Shouldn&#39;t it skip forward? Let&#39;s look at what <a href="perlfunc.html#pack">&quot;pack&quot; in perlfunc</a> says:</p>

<pre><code class="plaintext">x   A null byte.</code></pre>

<p>Urgh. No wonder. There&#39;s a big difference between &quot;a null byte&quot;, character zero, and &quot;a space&quot;, character 32. Perl&#39;s put something between the date and the description - but unfortunately, we can&#39;t see it!</p>

<p>What we actually need to do is expand the width of the fields. The <code>A</code> format pads any non-existent characters with spaces, so we can use the additional spaces to line up our fields, like this:</p>

<pre><code>print pack(&quot;A11 A28 A8 A*&quot;, $date, &quot;Totals&quot;,
    $tot_income, $tot_expend);</code></pre>

<p>(Note that you can put spaces in the template to make it more readable, but they don&#39;t translate to spaces in the output.) Here&#39;s what we got this time:</p>

<pre><code class="plaintext">01/24/2001 Zed&#39;s Camel Emporium                     1147.99
01/28/2001 Flea spray                                 24.99
01/29/2001 Camel rides to tourists     1235.00
03/23/2001 Totals                      1235.00 1172.98</code></pre>

<p>That&#39;s a bit better, but we still have that last column which needs to be moved further over. There&#39;s an easy way to fix this up: unfortunately, we can&#39;t get <code>pack</code> to right-justify our fields, but we can get <code>sprintf</code> to do it:</p>

<pre><code>$tot_income = sprintf(&quot;%.2f&quot;, $tot_income); 
$tot_expend = sprintf(&quot;%12.2f&quot;, $tot_expend);
$date = POSIX::strftime(&quot;%m/%d/%Y&quot;, localtime); 
print pack(&quot;A11 A28 A8 A*&quot;, $date, &quot;Totals&quot;,
    $tot_income, $tot_expend);</code></pre>

<p>This time we get the right answer:</p>

<pre><code class="plaintext">01/28/2001 Flea spray                                 24.99
01/29/2001 Camel rides to tourists     1235.00
03/23/2001 Totals                      1235.00      1172.98</code></pre>

<p>So that&#39;s how we consume and produce fixed-width data. Let&#39;s recap what we&#39;ve seen of <code>pack</code> and <code>unpack</code> so far:</p>

<ul>

<li><p>Use <code>pack</code> to go from several pieces of data to one fixed-width version; use <code>unpack</code> to turn a fixed-width-format string into several pieces of data.</p>

</li>
<li><p>The pack format <code>A</code> means &quot;any character&quot;; if you&#39;re <code>pack</code>ing and you&#39;ve run out of things to pack, <code>pack</code> will fill the rest up with spaces.</p>

</li>
<li><p><code>x</code> means &quot;skip a byte&quot; when <code>unpack</code>ing; when <code>pack</code>ing, it means &quot;introduce a null byte&quot; - that&#39;s probably not what you mean if you&#39;re dealing with plain text.</p>

</li>
<li><p>You can follow the formats with numbers to say how many characters should be affected by that format: <code>A12</code> means &quot;take 12 characters&quot;; <code>x6</code> means &quot;skip 6 bytes&quot; or &quot;character 0, 6 times&quot;.</p>

</li>
<li><p>Instead of a number, you can use <code>*</code> to mean &quot;consume everything else left&quot;.</p>

<p><b>Warning</b>: when packing multiple pieces of data, <code>*</code> only means &quot;consume all of the current piece of data&quot;. That&#39;s to say</p>

<pre><code>pack(&quot;A*A*&quot;, $one, $two)</code></pre>

<p>packs all of <code>$one</code> into the first <code>A*</code> and then all of <code>$two</code> into the second. This is a general principle: each format character corresponds to one piece of data to be <code>pack</code>ed.</p>

</li>
</ul>

<h1 id="Packing-Numbers"><a class="permalink" href="perlpacktut.html#Packing-Numbers">#</a><a id="Packing1"></a>Packing Numbers</h1>

<p>So much for textual data. Let&#39;s get onto the meaty stuff that <code>pack</code> and <code>unpack</code> are best at: handling binary formats for numbers. There is, of course, not just one binary format - life would be too simple - but Perl will do all the finicky labor for you.</p>

<h2 id="Integers"><a class="permalink" href="perlpacktut.html#Integers">#</a>Integers</h2>

<p>Packing and unpacking numbers implies conversion to and from some <i>specific</i> binary representation. Leaving floating point numbers aside for the moment, the salient properties of any such representation are:</p>

<ul>

<li><p>the number of bytes used for storing the integer,</p>

</li>
<li><p>whether the contents are interpreted as a signed or unsigned number,</p>

</li>
<li><p>the byte ordering: whether the first byte is the least or most significant byte (or: little-endian or big-endian, respectively).</p>

</li>
</ul>

<p>So, for instance, to pack 20302 to a signed 16 bit integer in your computer&#39;s representation you write</p>

<pre><code>my $ps = pack( &#39;s&#39;, 20302 );</code></pre>

<p>Again, the result is a string, now containing 2 bytes. If you print this string (which is, generally, not recommended) you might see <code>ON</code> or <code>NO</code> (depending on your system&#39;s byte ordering) - or something entirely different if your computer doesn&#39;t use ASCII character encoding. Unpacking <code>$ps</code> with the same template returns the original integer value:</p>

<pre><code>my( $s ) = unpack( &#39;s&#39;, $ps );</code></pre>

<p>This is true for all numeric template codes. But don&#39;t expect miracles: if the packed value exceeds the allotted byte capacity, high order bits are silently discarded, and unpack certainly won&#39;t be able to pull them back out of some magic hat. And, when you pack using a signed template code such as <code>s</code>, an excess value may result in the sign bit getting set, and unpacking this will smartly return a negative value.</p>

<p>16 bits won&#39;t get you too far with integers, but there is <code>l</code> and <code>L</code> for signed and unsigned 32-bit integers. And if this is not enough and your system supports 64 bit integers you can push the limits much closer to infinity with pack codes <code>q</code> and <code>Q</code>. A notable exception is provided by pack codes <code>i</code> and <code>I</code> for signed and unsigned integers of the &quot;local custom&quot; variety: Such an integer will take up as many bytes as a local C compiler returns for <code>sizeof(int)</code>, but it&#39;ll use <i>at least</i> 32 bits.</p>

<p>Each of the integer pack codes <code>sSlLqQ</code> results in a fixed number of bytes, no matter where you execute your program. This may be useful for some applications, but it does not provide for a portable way to pass data structures between Perl and C programs (bound to happen when you call XS extensions or the Perl function <code>syscall</code>), or when you read or write binary files. What you&#39;ll need in this case are template codes that depend on what your local C compiler compiles when you code <code>short</code> or <code>unsigned long</code>, for instance. These codes and their corresponding byte lengths are shown in the table below. Since the C standard leaves much leeway with respect to the relative sizes of these data types, actual values may vary, and that&#39;s why the values are given as expressions in C and Perl. (If you&#39;d like to use values from <code>%Config</code> in your program you have to import it with <code>use Config</code>.)</p>

<pre><code>signed unsigned  byte length in C   byte length in Perl       
  s!     S!      sizeof(short)      $Config{shortsize}
  i!     I!      sizeof(int)        $Config{intsize}
  l!     L!      sizeof(long)       $Config{longsize}
  q!     Q!      sizeof(long long)  $Config{longlongsize}</code></pre>

<p>The <code>i!</code> and <code>I!</code> codes aren&#39;t different from <code>i</code> and <code>I</code>; they are tolerated for completeness&#39; sake.</p>

<h2 id="Unpacking-a-Stack-Frame"><a class="permalink" href="perlpacktut.html#Unpacking-a-Stack-Frame">#</a><a id="Unpacking"></a>Unpacking a Stack Frame</h2>

<p>Requesting a particular byte ordering may be necessary when you work with binary data coming from some specific architecture whereas your program could run on a totally different system. As an example, assume you have 24 bytes containing a stack frame as it happens on an Intel 8086:</p>

<pre><code class="plaintext">     +---------+        +----+----+               +---------+
TOS: |   IP    |  TOS+4:| FL | FH | FLAGS  TOS+14:|   SI    |
     +---------+        +----+----+               +---------+
     |   CS    |        | AL | AH | AX            |   DI    |
     +---------+        +----+----+               +---------+
                        | BL | BH | BX            |   BP    |
                        +----+----+               +---------+
                        | CL | CH | CX            |   DS    |
                        +----+----+               +---------+
                        | DL | DH | DX            |   ES    |
                        +----+----+               +---------+</code></pre>

<p>First, we note that this time-honored 16-bit CPU uses little-endian order, and that&#39;s why the low order byte is stored at the lower address. To unpack such a (unsigned) short we&#39;ll have to use code <code>v</code>. A repeat count unpacks all 12 shorts:</p>

<pre><code>my( $ip, $cs, $flags, $ax, $bx, $cx, $dx, $si, $di, $bp, $ds, $es ) =
  unpack( &#39;v12&#39;, $frame );</code></pre>

<p>Alternatively, we could have used <code>C</code> to unpack the individually accessible byte registers FL, FH, AL, AH, etc.:</p>

<pre><code>my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) =
  unpack( &#39;C10&#39;, substr( $frame, 4, 10 ) );</code></pre>

<p>It would be nice if we could do this in one fell swoop: unpack a short, back up a little, and then unpack 2 bytes. Since Perl <i>is</i> nice, it proffers the template code <code>X</code> to back up one byte. Putting this all together, we may now write:</p>

<pre><code>my( $ip, $cs,
    $flags,$fl,$fh,
    $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh, 
    $si, $di, $bp, $ds, $es ) =
unpack( &#39;v2&#39; . (&#39;vXXCC&#39; x 5) . &#39;v5&#39;, $frame );</code></pre>

<p>(The clumsy construction of the template can be avoided - just read on!)</p>

<p>We&#39;ve taken some pains to construct the template so that it matches the contents of our frame buffer. Otherwise we&#39;d either get undefined values, or <code>unpack</code> could not unpack all. If <code>pack</code> runs out of items, it will supply null strings (which are coerced into zeroes whenever the pack code says so).</p>

<h2 id="How-to-Eat-an-Egg-on-a-Net"><a class="permalink" href="perlpacktut.html#How-to-Eat-an-Egg-on-a-Net">#</a><a id="How"></a>How to Eat an Egg on a Net</h2>

<p>The pack code for big-endian (high order byte at the lowest address) is <code>n</code> for 16 bit and <code>N</code> for 32 bit integers. You use these codes if you know that your data comes from a compliant architecture, but, surprisingly enough, you should also use these pack codes if you exchange binary data, across the network, with some system that you know next to nothing about. The simple reason is that this order has been chosen as the <i>network order</i>, and all standard-fearing programs ought to follow this convention. (This is, of course, a stern backing for one of the Lilliputian parties and may well influence the political development there.) So, if the protocol expects you to send a message by sending the length first, followed by just so many bytes, you could write:</p>

<pre><code>my $buf = pack( &#39;N&#39;, length( $msg ) ) . $msg;</code></pre>

<p>or even:</p>

<pre><code>my $buf = pack( &#39;NA*&#39;, length( $msg ), $msg );</code></pre>

<p>and pass <code>$buf</code> to your send routine. Some protocols demand that the count should include the length of the count itself: then just add 4 to the data length. (But make sure to read <a href="perlpacktut.html#Lengths-and-Widths">&quot;Lengths and Widths&quot;</a> before you really code this!)</p>

<h2 id="Byte-order-modifiers"><a class="permalink" href="perlpacktut.html#Byte-order-modifiers">#</a><a id="Byte"></a>Byte-order modifiers</h2>

<p>In the previous sections we&#39;ve learned how to use <code>n</code>, <code>N</code>, <code>v</code> and <code>V</code> to pack and unpack integers with big- or little-endian byte-order. While this is nice, it&#39;s still rather limited because it leaves out all kinds of signed integers as well as 64-bit integers. For example, if you wanted to unpack a sequence of signed big-endian 16-bit integers in a platform-independent way, you would have to write:</p>

<pre><code>my @data = unpack &#39;s*&#39;, pack &#39;S*&#39;, unpack &#39;n*&#39;, $buf;</code></pre>

<p>This is ugly. As of Perl 5.9.2, there&#39;s a much nicer way to express your desire for a certain byte-order: the <code>&gt;</code> and <code>&lt;</code> modifiers. <code>&gt;</code> is the big-endian modifier, while <code>&lt;</code> is the little-endian modifier. Using them, we could rewrite the above code as:</p>

<pre><code>my @data = unpack &#39;s&gt;*&#39;, $buf;</code></pre>

<p>As you can see, the &quot;big end&quot; of the arrow touches the <code>s</code>, which is a nice way to remember that <code>&gt;</code> is the big-endian modifier. The same obviously works for <code>&lt;</code>, where the &quot;little end&quot; touches the code.</p>

<p>You will probably find these modifiers even more useful if you have to deal with big- or little-endian C structures. Be sure to read <a href="perlpacktut.html#Packing-and-Unpacking-C-Structures">&quot;Packing and Unpacking C Structures&quot;</a> for more on that.</p>

<h2 id="Floating-point-Numbers"><a class="permalink" href="perlpacktut.html#Floating-point-Numbers">#</a><a id="Floating"></a>Floating point Numbers</h2>

<p>For packing floating point numbers you have the choice between the pack codes <code>f</code>, <code>d</code>, <code>F</code> and <code>D</code>. <code>f</code> and <code>d</code> pack into (or unpack from) single-precision or double-precision representation as it is provided by your system. If your systems supports it, <code>D</code> can be used to pack and unpack (<code>long double</code>) values, which can offer even more resolution than <code>f</code> or <code>d</code>. <b>Note that there are different long double formats.</b></p>

<p><code>F</code> packs an <code>NV</code>, which is the floating point type used by Perl internally.</p>

<p>There is no such thing as a network representation for reals, so if you want to send your real numbers across computer boundaries, you&#39;d better stick to text representation, possibly using the hexadecimal float format (avoiding the decimal conversion loss), unless you&#39;re absolutely sure what&#39;s on the other end of the line. For the even more adventuresome, you can use the byte-order modifiers from the previous section also on floating point codes.</p>

<h1 id="Exotic-Templates"><a class="permalink" href="perlpacktut.html#Exotic-Templates">#</a><a id="Exotic"></a>Exotic Templates</h1>

<h2 id="Bit-Strings"><a class="permalink" href="perlpacktut.html#Bit-Strings">#</a><a id="Bit"></a>Bit Strings</h2>

<p>Bits are the atoms in the memory world. Access to individual bits may have to be used either as a last resort or because it is the most convenient way to handle your data. Bit string (un)packing converts between strings containing a series of <code>0</code> and <code>1</code> characters and a sequence of bytes each containing a group of 8 bits. This is almost as simple as it sounds, except that there are two ways the contents of a byte may be written as a bit string. Let&#39;s have a look at an annotated byte:</p>

<pre><code class="plaintext">  7 6 5 4 3 2 1 0
+-----------------+
| 1 0 0 0 1 1 0 0 |
+-----------------+
 MSB           LSB</code></pre>

<p>It&#39;s egg-eating all over again: Some think that as a bit string this should be written &quot;10001100&quot; i.e. beginning with the most significant bit, others insist on &quot;00110001&quot;. Well, Perl isn&#39;t biased, so that&#39;s why we have two bit string codes:</p>

<pre><code>$byte = pack( &#39;B8&#39;, &#39;10001100&#39; ); # start with MSB
$byte = pack( &#39;b8&#39;, &#39;00110001&#39; ); # start with LSB</code></pre>

<p>It is not possible to pack or unpack bit fields - just integral bytes. <code>pack</code> always starts at the next byte boundary and &quot;rounds up&quot; to the next multiple of 8 by adding zero bits as required. (If you do want bit fields, there is <a href="perlfunc.html#vec">&quot;vec&quot; in perlfunc</a>. Or you could implement bit field handling at the character string level, using split, substr, and concatenation on unpacked bit strings.)</p>

<p>To illustrate unpacking for bit strings, we&#39;ll decompose a simple status register (a &quot;-&quot; stands for a &quot;reserved&quot; bit):</p>

<pre><code class="plaintext">+-----------------+-----------------+
| S Z - A - P - C | - - - - O D I T |
+-----------------+-----------------+
 MSB           LSB MSB           LSB</code></pre>

<p>Converting these two bytes to a string can be done with the unpack template <code>&#39;b16&#39;</code>. To obtain the individual bit values from the bit string we use <code>split</code> with the &quot;empty&quot; separator pattern which dissects into individual characters. Bit values from the &quot;reserved&quot; positions are simply assigned to <code>undef</code>, a convenient notation for &quot;I don&#39;t care where this goes&quot;.</p>

<pre><code>($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign,
 $trace, $interrupt, $direction, $overflow) =
   split( //, unpack( &#39;b16&#39;, $status ) );</code></pre>

<p>We could have used an unpack template <code>&#39;b12&#39;</code> just as well, since the last 4 bits can be ignored anyway.</p>

<h2 id="Uuencoding"><a class="permalink" href="perlpacktut.html#Uuencoding">#</a>Uuencoding</h2>

<p>Another odd-man-out in the template alphabet is <code>u</code>, which packs a &quot;uuencoded string&quot;. (&quot;uu&quot; is short for Unix-to-Unix.) Chances are that you won&#39;t ever need this encoding technique which was invented to overcome the shortcomings of old-fashioned transmission mediums that do not support other than simple ASCII data. The essential recipe is simple: Take three bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to each. Repeat until all of the data is blended. Fold groups of 4 bytes into lines no longer than 60 and garnish them in front with the original byte count (incremented by 0x20) and a <code>&quot;\n&quot;</code> at the end. - The <code>pack</code> chef will prepare this for you, a la minute, when you select pack code <code>u</code> on the menu:</p>

<pre><code>my $uubuf = pack( &#39;u&#39;, $bindat );</code></pre>

<p>A repeat count after <code>u</code> sets the number of bytes to put into an uuencoded line, which is the maximum of 45 by default, but could be set to some (smaller) integer multiple of three. <code>unpack</code> simply ignores the repeat count.</p>

<h2 id="Doing-Sums"><a class="permalink" href="perlpacktut.html#Doing-Sums">#</a><a id="Doing"></a>Doing Sums</h2>

<p>An even stranger template code is <code>%</code>&lt;<i>number</i>&gt;. First, because it&#39;s used as a prefix to some other template code. Second, because it cannot be used in <code>pack</code> at all, and third, in <code>unpack</code>, doesn&#39;t return the data as defined by the template code it precedes. Instead it&#39;ll give you an integer of <i>number</i> bits that is computed from the data value by doing sums. For numeric unpack codes, no big feat is achieved:</p>

<pre><code>my $buf = pack( &#39;iii&#39;, 100, 20, 3 );
print unpack( &#39;%32i3&#39;, $buf ), &quot;\n&quot;;  # prints 123</code></pre>

<p>For string values, <code>%</code> returns the sum of the byte values saving you the trouble of a sum loop with <code>substr</code> and <code>ord</code>:</p>

<pre><code>print unpack( &#39;%32A*&#39;, &quot;\x01\x10&quot; ), &quot;\n&quot;;  # prints 17</code></pre>

<p>Although the <code>%</code> code is documented as returning a &quot;checksum&quot;: don&#39;t put your trust in such values! Even when applied to a small number of bytes, they won&#39;t guarantee a noticeable Hamming distance.</p>

<p>In connection with <code>b</code> or <code>B</code>, <code>%</code> simply adds bits, and this can be put to good use to count set bits efficiently:</p>

<pre><code>my $bitcount = unpack( &#39;%32b*&#39;, $mask );</code></pre>

<p>And an even parity bit can be determined like this:</p>

<pre><code>my $evenparity = unpack( &#39;%1b*&#39;, $mask );</code></pre>

<h2 id="Unicode"><a class="permalink" href="perlpacktut.html#Unicode">#</a>Unicode</h2>

<p>Unicode is a character set that can represent most characters in most of the world&#39;s languages, providing room for over one million different characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with characters that are used in several European languages is in the next range, up to 255. After some more Latin extensions we find the character sets from languages using non-Roman alphabets, interspersed with a variety of symbol sets such as currency symbols, Zapf Dingbats or Braille. (You might want to visit <a href="https://www.unicode.org/">https://www.unicode.org/</a> for a look at some of them - my personal favourites are Telugu and Kannada.)</p>

<p>The Unicode character sets associates characters with integers. Encoding these numbers in an equal number of bytes would more than double the requirements for storing texts written in Latin alphabets. The UTF-8 encoding avoids this by storing the most common (from a western point of view) characters in a single byte while encoding the rarer ones in three or more bytes.</p>

<p>Perl uses UTF-8, internally, for most Unicode strings.</p>

<p>So what has this got to do with <code>pack</code>? Well, if you want to compose a Unicode string (that is internally encoded as UTF-8), you can do so by using template code <code>U</code>. As an example, let&#39;s produce the Euro currency symbol (code number 0x20AC):</p>

<pre><code>$UTF8{Euro} = pack( &#39;U&#39;, 0x20AC );
# Equivalent to: $UTF8{Euro} = &quot;\x{20ac}&quot;;</code></pre>

<p>Inspecting <code>$UTF8{Euro}</code> shows that it contains 3 bytes: &quot;\xe2\x82\xac&quot;. However, it contains only 1 character, number 0x20AC. The round trip can be completed with <code>unpack</code>:</p>

<pre><code>$Unicode{Euro} = unpack( &#39;U&#39;, $UTF8{Euro} );</code></pre>

<p>Unpacking using the <code>U</code> template code also works on UTF-8 encoded byte strings.</p>

<p>Usually you&#39;ll want to pack or unpack UTF-8 strings:</p>

<pre><code># pack and unpack the Hebrew alphabet
my $alefbet = pack( &#39;U*&#39;, 0x05d0..0x05ea );
my @hebrew = unpack( &#39;U*&#39;, $utf );</code></pre>

<p>Please note: in the general case, you&#39;re better off using <a href="Encode.html#decode"><code>Encode::decode(&#39;UTF-8&#39;, $utf)</code></a> to decode a UTF-8 encoded byte string to a Perl Unicode string, and <a href="Encode.html#encode"><code>Encode::encode(&#39;UTF-8&#39;, $str)</code></a> to encode a Perl Unicode string to UTF-8 bytes. These functions provide means of handling invalid byte sequences and generally have a friendlier interface.</p>

<h2 id="Another-Portable-Binary-Encoding"><a class="permalink" href="perlpacktut.html#Another-Portable-Binary-Encoding">#</a><a id="Another"></a>Another Portable Binary Encoding</h2>

<p>The pack code <code>w</code> has been added to support a portable binary data encoding scheme that goes way beyond simple integers. (Details can be found at <a href="https://github.com/mworks-project/mw_scarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt">https://github.com/mworks-project/mw_scarab/blob/master/Scarab-0.1.00d19/doc/binary-serialization.txt</a>, the Scarab project.) A BER (Binary Encoded Representation) compressed unsigned integer stores base 128 digits, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last. There is no size limit to BER encoding, but Perl won&#39;t go to extremes.</p>

<pre><code>my $berbuf = pack( &#39;w*&#39;, 1, 128, 128+1, 128*128+127 );</code></pre>

<p>A hex dump of <code>$berbuf</code>, with spaces inserted at the right places, shows 01 8100 8101 81807F. Since the last byte is always less than 128, <code>unpack</code> knows where to stop.</p>

<h1 id="Template-Grouping"><a class="permalink" href="perlpacktut.html#Template-Grouping">#</a><a id="Template"></a>Template Grouping</h1>

<p>Prior to Perl 5.8, repetitions of templates had to be made by <code>x</code>-multiplication of template strings. Now there is a better way as we may use the pack codes <code>(</code> and <code>)</code> combined with a repeat count. The <code>unpack</code> template from the Stack Frame example can simply be written like this:</p>

<pre><code>unpack( &#39;v2 (vXXCC)5 v5&#39;, $frame )</code></pre>

<p>Let&#39;s explore this feature a little more. We&#39;ll begin with the equivalent of</p>

<pre><code>join( &#39;&#39;, map( substr( $_, 0, 1 ), @str ) )</code></pre>

<p>which returns a string consisting of the first character from each string. Using pack, we can write</p>

<pre><code>pack( &#39;(A)&#39;.@str, @str )</code></pre>

<p>or, because a repeat count <code>*</code> means &quot;repeat as often as required&quot;, simply</p>

<pre><code>pack( &#39;(A)*&#39;, @str )</code></pre>

<p>(Note that the template <code>A*</code> would only have packed <code>$str[0]</code> in full length.)</p>

<p>To pack dates stored as triplets ( day, month, year ) in an array <code>@dates</code> into a sequence of byte, byte, short integer we can write</p>

<pre><code>$pd = pack( &#39;(CCS)*&#39;, map( @$_, @dates ) );</code></pre>

<p>To swap pairs of characters in a string (with even length) one could use several techniques. First, let&#39;s use <code>x</code> and <code>X</code> to skip forward and back:</p>

<pre><code>$s = pack( &#39;(A)*&#39;, unpack( &#39;(xAXXAx)*&#39;, $s ) );</code></pre>

<p>We can also use <code>@</code> to jump to an offset, with 0 being the position where we were when the last <code>(</code> was encountered:</p>

<pre><code>$s = pack( &#39;(A)*&#39;, unpack( &#39;(@1A @0A @2)*&#39;, $s ) );</code></pre>

<p>Finally, there is also an entirely different approach by unpacking big endian shorts and packing them in the reverse byte order:</p>

<pre><code>$s = pack( &#39;(v)*&#39;, unpack( &#39;(n)*&#39;, $s );</code></pre>

<h1 id="Lengths-and-Widths"><a class="permalink" href="perlpacktut.html#Lengths-and-Widths">#</a><a id="Lengths"></a>Lengths and Widths</h1>

<h2 id="String-Lengths"><a class="permalink" href="perlpacktut.html#String-Lengths">#</a><a id="String"></a>String Lengths</h2>

<p>In the previous section we&#39;ve seen a network message that was constructed by prefixing the binary message length to the actual message. You&#39;ll find that packing a length followed by so many bytes of data is a frequently used recipe since appending a null byte won&#39;t work if a null byte may be part of the data. Here is an example where both techniques are used: after two null terminated strings with source and destination address, a Short Message (to a mobile phone) is sent after a length byte:</p>

<pre><code>my $msg = pack( &#39;Z*Z*CA*&#39;, $src, $dst, length( $sm ), $sm );</code></pre>

<p>Unpacking this message can be done with the same template:</p>

<pre><code>( $src, $dst, $len, $sm ) = unpack( &#39;Z*Z*CA*&#39;, $msg );</code></pre>

<p>There&#39;s a subtle trap lurking in the offing: Adding another field after the Short Message (in variable <code>$sm</code>) is all right when packing, but this cannot be unpacked naively:</p>

<pre><code># pack a message
my $msg = pack( &#39;Z*Z*CA*C&#39;, $src, $dst, length( $sm ), $sm, $prio );

# unpack fails - $prio remains undefined!
( $src, $dst, $len, $sm, $prio ) = unpack( &#39;Z*Z*CA*C&#39;, $msg );</code></pre>

<p>The pack code <code>A*</code> gobbles up all remaining bytes, and <code>$prio</code> remains undefined! Before we let disappointment dampen the morale: Perl&#39;s got the trump card to make this trick too, just a little further up the sleeve. Watch this:</p>

<pre><code># pack a message: ASCIIZ, ASCIIZ, length/string, byte
my $msg = pack( &#39;Z* Z* C/A* C&#39;, $src, $dst, $sm, $prio );

# unpack
( $src, $dst, $sm, $prio ) = unpack( &#39;Z* Z* C/A* C&#39;, $msg );</code></pre>

<p>Combining two pack codes with a slash (<code>/</code>) associates them with a single value from the argument list. In <code>pack</code>, the length of the argument is taken and packed according to the first code while the argument itself is added after being converted with the template code after the slash. This saves us the trouble of inserting the <code>length</code> call, but it is in <code>unpack</code> where we really score: The value of the length byte marks the end of the string to be taken from the buffer. Since this combination doesn&#39;t make sense except when the second pack code isn&#39;t <code>a*</code>, <code>A*</code> or <code>Z*</code>, Perl won&#39;t let you.</p>

<p>The pack code preceding <code>/</code> may be anything that&#39;s fit to represent a number: All the numeric binary pack codes, and even text codes such as <code>A4</code> or <code>Z*</code>:</p>

<pre><code># pack/unpack a string preceded by its length in ASCII
my $buf = pack( &#39;A4/A*&#39;, &quot;Humpty-Dumpty&quot; );
# unpack $buf: &#39;13  Humpty-Dumpty&#39;
my $txt = unpack( &#39;A4/A*&#39;, $buf );</code></pre>

<p><code>/</code> is not implemented in Perls before 5.6, so if your code is required to work on ancient Perls you&#39;ll need to <code>unpack( &#39;Z* Z* C&#39;)</code> to get the length, then use it to make a new unpack string. For example</p>

<pre><code># pack a message: ASCIIZ, ASCIIZ, length, string, byte
# (5.005 compatible)
my $msg = pack( &#39;Z* Z* C A* C&#39;, $src, $dst, length $sm, $sm, $prio );

# unpack
( undef, undef, $len) = unpack( &#39;Z* Z* C&#39;, $msg );
($src, $dst, $sm, $prio) = unpack ( &quot;Z* Z* x A$len C&quot;, $msg );</code></pre>

<p>But that second <code>unpack</code> is rushing ahead. It isn&#39;t using a simple literal string for the template. So maybe we should introduce...</p>

<h2 id="Dynamic-Templates"><a class="permalink" href="perlpacktut.html#Dynamic-Templates">#</a><a id="Dynamic"></a>Dynamic Templates</h2>

<p>So far, we&#39;ve seen literals used as templates. If the list of pack items doesn&#39;t have fixed length, an expression constructing the template is required (whenever, for some reason, <code>()*</code> cannot be used). Here&#39;s an example: To store named string values in a way that can be conveniently parsed by a C program, we create a sequence of names and null terminated ASCII strings, with <code>=</code> between the name and the value, followed by an additional delimiting null byte. Here&#39;s how:</p>

<pre><code>my $env = pack( &#39;(A*A*Z*)&#39; . keys( %Env ) . &#39;C&#39;,
                map( { ( $_, &#39;=&#39;, $Env{$_} ) } keys( %Env ) ), 0 );</code></pre>

<p>Let&#39;s examine the cogs of this byte mill, one by one. There&#39;s the <code>map</code> call, creating the items we intend to stuff into the <code>$env</code> buffer: to each key (in <code>$_</code>) it adds the <code>=</code> separator and the hash entry value. Each triplet is packed with the template code sequence <code>A*A*Z*</code> that is repeated according to the number of keys. (Yes, that&#39;s what the <code>keys</code> function returns in scalar context.) To get the very last null byte, we add a <code>0</code> at the end of the <code>pack</code> list, to be packed with <code>C</code>. (Attentive readers may have noticed that we could have omitted the 0.)</p>

<p>For the reverse operation, we&#39;ll have to determine the number of items in the buffer before we can let <code>unpack</code> rip it apart:</p>

<pre><code>my $n = $env =~ tr/\0// - 1;
my %env = map( split( /=/, $_ ), unpack( &quot;(Z*)$n&quot;, $env ) );</code></pre>

<p>The <code>tr</code> counts the null bytes. The <code>unpack</code> call returns a list of name-value pairs each of which is taken apart in the <code>map</code> block.</p>

<h2 id="Counting-Repetitions"><a class="permalink" href="perlpacktut.html#Counting-Repetitions">#</a><a id="Counting"></a>Counting Repetitions</h2>

<p>Rather than storing a sentinel at the end of a data item (or a list of items), we could precede the data with a count. Again, we pack keys and values of a hash, preceding each with an unsigned short length count, and up front we store the number of pairs:</p>

<pre><code>my $env = pack( &#39;S(S/A* S/A*)*&#39;, scalar keys( %Env ), %Env );</code></pre>

<p>This simplifies the reverse operation as the number of repetitions can be unpacked with the <code>/</code> code:</p>

<pre><code>my %env = unpack( &#39;S/(S/A* S/A*)&#39;, $env );</code></pre>

<p>Note that this is one of the rare cases where you cannot use the same template for <code>pack</code> and <code>unpack</code> because <code>pack</code> can&#39;t determine a repeat count for a <code>()</code>-group.</p>

<h2 id="Intel-HEX"><a class="permalink" href="perlpacktut.html#Intel-HEX">#</a><a id="Intel"></a>Intel HEX</h2>

<p>Intel HEX is a file format for representing binary data, mostly for programming various chips, as a text file. (See <a href="https://en.wikipedia.org/wiki/.hex">https://en.wikipedia.org/wiki/.hex</a> for a detailed description, and <a href="https://en.wikipedia.org/wiki/SREC_(file_format)">https://en.wikipedia.org/wiki/SREC_(file_format)</a> for the Motorola S-record format, which can be unravelled using the same technique.) Each line begins with a colon (&#39;:&#39;) and is followed by a sequence of hexadecimal characters, specifying a byte count <i>n</i> (8 bit), an address (16 bit, big endian), a record type (8 bit), <i>n</i> data bytes and a checksum (8 bit) computed as the least significant byte of the two&#39;s complement sum of the preceding bytes. Example: <code>:0300300002337A1E</code>.</p>

<p>The first step of processing such a line is the conversion, to binary, of the hexadecimal data, to obtain the four fields, while checking the checksum. No surprise here: we&#39;ll start with a simple <code>pack</code> call to convert everything to binary:</p>

<pre><code>my $binrec = pack( &#39;H*&#39;, substr( $hexrec, 1 ) );</code></pre>

<p>The resulting byte sequence is most convenient for checking the checksum. Don&#39;t slow your program down with a for loop adding the <code>ord</code> values of this string&#39;s bytes - the <code>unpack</code> code <code>%</code> is the thing to use for computing the 8-bit sum of all bytes, which must be equal to zero:</p>

<pre><code>die unless unpack( &quot;%8C*&quot;, $binrec ) == 0;</code></pre>

<p>Finally, let&#39;s get those four fields. By now, you shouldn&#39;t have any problems with the first three fields - but how can we use the byte count of the data in the first field as a length for the data field? Here the codes <code>x</code> and <code>X</code> come to the rescue, as they permit jumping back and forth in the string to unpack.</p>

<pre><code>my( $addr, $type, $data ) = unpack( &quot;x n C X4 C x3 /a&quot;, $bin ); </code></pre>

<p>Code <code>x</code> skips a byte, since we don&#39;t need the count yet. Code <code>n</code> takes care of the 16-bit big-endian integer address, and <code>C</code> unpacks the record type. Being at offset 4, where the data begins, we need the count. <code>X4</code> brings us back to square one, which is the byte at offset 0. Now we pick up the count, and zoom forth to offset 4, where we are now fully furnished to extract the exact number of data bytes, leaving the trailing checksum byte alone.</p>

<h1 id="Packing-and-Unpacking-C-Structures"><a class="permalink" href="perlpacktut.html#Packing-and-Unpacking-C-Structures">#</a><a id="Packing2"></a>Packing and Unpacking C Structures</h1>

<p>In previous sections we have seen how to pack numbers and character strings. If it were not for a couple of snags we could conclude this section right away with the terse remark that C structures don&#39;t contain anything else, and therefore you already know all there is to it. Sorry, no: read on, please.</p>

<p>If you have to deal with a lot of C structures, and don&#39;t want to hack all your template strings manually, you&#39;ll probably want to have a look at the CPAN module <code>Convert::Binary::C</code>. Not only can it parse your C source directly, but it also has built-in support for all the odds and ends described further on in this section.</p>

<h2 id="The-Alignment-Pit"><a class="permalink" href="perlpacktut.html#The-Alignment-Pit">#</a><a id="The1"></a>The Alignment Pit</h2>

<p>In the consideration of speed against memory requirements the balance has been tilted in favor of faster execution. This has influenced the way C compilers allocate memory for structures: On architectures where a 16-bit or 32-bit operand can be moved faster between places in memory, or to or from a CPU register, if it is aligned at an even or multiple-of-four or even at a multiple-of eight address, a C compiler will give you this speed benefit by stuffing extra bytes into structures. If you don&#39;t cross the C shoreline this is not likely to cause you any grief (although you should care when you design large data structures, or you want your code to be portable between architectures (you do want that, don&#39;t you?)).</p>

<p>To see how this affects <code>pack</code> and <code>unpack</code>, we&#39;ll compare these two C structures:</p>

<pre><code>typedef struct {
  char     c1;
  short    s;
  char     c2;
  long     l;
} gappy_t;

typedef struct {
  long     l;
  short    s;
  char     c1;
  char     c2;
} dense_t;</code></pre>

<p>Typically, a C compiler allocates 12 bytes to a <code>gappy_t</code> variable, but requires only 8 bytes for a <code>dense_t</code>. After investigating this further, we can draw memory maps, showing where the extra 4 bytes are hidden:</p>

<pre><code class="plaintext">0           +4          +8          +12
+--+--+--+--+--+--+--+--+--+--+--+--+
|c1|xx|  s  |c2|xx|xx|xx|     l     |    xx = fill byte
+--+--+--+--+--+--+--+--+--+--+--+--+
gappy_t

0           +4          +8
+--+--+--+--+--+--+--+--+
|     l     |  h  |c1|c2|
+--+--+--+--+--+--+--+--+
dense_t</code></pre>

<p>And that&#39;s where the first quirk strikes: <code>pack</code> and <code>unpack</code> templates have to be stuffed with <code>x</code> codes to get those extra fill bytes.</p>

<p>The natural question: &quot;Why can&#39;t Perl compensate for the gaps?&quot; warrants an answer. One good reason is that C compilers might provide (non-ANSI) extensions permitting all sorts of fancy control over the way structures are aligned, even at the level of an individual structure field. And, if this were not enough, there is an insidious thing called <code>union</code> where the amount of fill bytes cannot be derived from the alignment of the next item alone.</p>

<p>OK, so let&#39;s bite the bullet. Here&#39;s one way to get the alignment right by inserting template codes <code>x</code>, which don&#39;t take a corresponding item from the list:</p>

<pre><code>my $gappy = pack( &#39;cxs cxxx l!&#39;, $c1, $s, $c2, $l );</code></pre>

<p>Note the <code>!</code> after <code>l</code>: We want to make sure that we pack a long integer as it is compiled by our C compiler. And even now, it will only work for the platforms where the compiler aligns things as above. And somebody somewhere has a platform where it doesn&#39;t. [Probably a Cray, where <code>short</code>s, <code>int</code>s and <code>long</code>s are all 8 bytes. :-)]</p>

<p>Counting bytes and watching alignments in lengthy structures is bound to be a drag. Isn&#39;t there a way we can create the template with a simple program? Here&#39;s a C program that does the trick:</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stddef.h&gt;

typedef struct {
  char     fc1;
  short    fs;
  char     fc2;
  long     fl;
} gappy_t;

#define Pt(struct,field,tchar) \
  printf( &quot;@%d%s &quot;, offsetof(struct,field), # tchar );

int main() {
  Pt( gappy_t, fc1, c  );
  Pt( gappy_t, fs,  s! );
  Pt( gappy_t, fc2, c  );
  Pt( gappy_t, fl,  l! );
  printf( &quot;\n&quot; );
}</code></pre>

<p>The output line can be used as a template in a <code>pack</code> or <code>unpack</code> call:</p>

<pre><code>my $gappy = pack( &#39;@0c @2s! @4c @8l!&#39;, $c1, $s, $c2, $l );</code></pre>

<p>Gee, yet another template code - as if we hadn&#39;t plenty. But <code>@</code> saves our day by enabling us to specify the offset from the beginning of the pack buffer to the next item: This is just the value the <code>offsetof</code> macro (defined in <code>&lt;stddef.h&gt;</code>) returns when given a <code>struct</code> type and one of its field names (&quot;member-designator&quot; in C standardese).</p>

<p>Neither using offsets nor adding <code>x</code>&#39;s to bridge the gaps is satisfactory. (Just imagine what happens if the structure changes.) What we really need is a way of saying &quot;skip as many bytes as required to the next multiple of N&quot;. In fluent templates, you say this with <code>x!N</code> where N is replaced by the appropriate value. Here&#39;s the next version of our struct packaging:</p>

<pre><code>my $gappy = pack( &#39;c x!2 s c x!4 l!&#39;, $c1, $s, $c2, $l );</code></pre>

<p>That&#39;s certainly better, but we still have to know how long all the integers are, and portability is far away. Rather than <code>2</code>, for instance, we want to say &quot;however long a short is&quot;. But this can be done by enclosing the appropriate pack code in brackets: <code>[s]</code>. So, here&#39;s the very best we can do:</p>

<pre><code>my $gappy = pack( &#39;c x![s] s c x![l!] l!&#39;, $c1, $s, $c2, $l );</code></pre>

<h2 id="Dealing-with-Endian-ness"><a class="permalink" href="perlpacktut.html#Dealing-with-Endian-ness">#</a><a id="Dealing"></a>Dealing with Endian-ness</h2>

<p>Now, imagine that we want to pack the data for a machine with a different byte-order. First, we&#39;ll have to figure out how big the data types on the target machine really are. Let&#39;s assume that the longs are 32 bits wide and the shorts are 16 bits wide. You can then rewrite the template as:</p>

<pre><code>my $gappy = pack( &#39;c x![s] s c x![l] l&#39;, $c1, $s, $c2, $l );</code></pre>

<p>If the target machine is little-endian, we could write:</p>

<pre><code>my $gappy = pack( &#39;c x![s] s&lt; c x![l] l&lt;&#39;, $c1, $s, $c2, $l );</code></pre>

<p>This forces the short and the long members to be little-endian, and is just fine if you don&#39;t have too many struct members. But we could also use the byte-order modifier on a group and write the following:</p>

<pre><code>my $gappy = pack( &#39;( c x![s] s c x![l] l )&lt;&#39;, $c1, $s, $c2, $l );</code></pre>

<p>This is not as short as before, but it makes it more obvious that we intend to have little-endian byte-order for a whole group, not only for individual template codes. It can also be more readable and easier to maintain.</p>

<h2 id="Alignment,-Take-2"><a class="permalink" href="perlpacktut.html#Alignment,-Take-2">#</a><a id="Alignment"></a><a id="Alignment-Take-2"></a>Alignment, Take 2</h2>

<p>I&#39;m afraid that we&#39;re not quite through with the alignment catch yet. The hydra raises another ugly head when you pack arrays of structures:</p>

<pre><code>typedef struct {
  short    count;
  char     glyph;
} cell_t;

typedef cell_t buffer_t[BUFLEN];</code></pre>

<p>Where&#39;s the catch? Padding is neither required before the first field <code>count</code>, nor between this and the next field <code>glyph</code>, so why can&#39;t we simply pack like this:</p>

<pre><code># something goes wrong here:
pack( &#39;s!a&#39; x @buffer,
      map{ ( $_-&gt;{count}, $_-&gt;{glyph} ) } @buffer );</code></pre>

<p>This packs <code>3*@buffer</code> bytes, but it turns out that the size of <code>buffer_t</code> is four times <code>BUFLEN</code>! The moral of the story is that the required alignment of a structure or array is propagated to the next higher level where we have to consider padding <i>at the end</i> of each component as well. Thus the correct template is:</p>

<pre><code>pack( &#39;s!ax&#39; x @buffer,
      map{ ( $_-&gt;{count}, $_-&gt;{glyph} ) } @buffer );</code></pre>

<h2 id="Alignment,-Take-3"><a class="permalink" href="perlpacktut.html#Alignment,-Take-3">#</a><a id="Alignment1"></a><a id="Alignment-Take-3"></a>Alignment, Take 3</h2>

<p>And even if you take all the above into account, ANSI still lets this:</p>

<pre><code>typedef struct {
  char     foo[2];
} foo_t;</code></pre>

<p>vary in size. The alignment constraint of the structure can be greater than any of its elements. [And if you think that this doesn&#39;t affect anything common, dismember the next cellphone that you see. Many have ARM cores, and the ARM structure rules make <code>sizeof (foo_t)</code> == 4]</p>

<h2 id="Pointers-for-How-to-Use-Them"><a class="permalink" href="perlpacktut.html#Pointers-for-How-to-Use-Them">#</a><a id="Pointers"></a>Pointers for How to Use Them</h2>

<p>The title of this section indicates the second problem you may run into sooner or later when you pack C structures. If the function you intend to call expects a, say, <code>void *</code> value, you <i>cannot</i> simply take a reference to a Perl variable. (Although that value certainly is a memory address, it&#39;s not the address where the variable&#39;s contents are stored.)</p>

<p>Template code <code>P</code> promises to pack a &quot;pointer to a fixed length string&quot;. Isn&#39;t this what we want? Let&#39;s try:</p>

<pre><code># allocate some storage and pack a pointer to it
my $memory = &quot;\x00&quot; x $size;
my $memptr = pack( &#39;P&#39;, $memory );</code></pre>

<p>But wait: doesn&#39;t <code>pack</code> just return a sequence of bytes? How can we pass this string of bytes to some C code expecting a pointer which is, after all, nothing but a number? The answer is simple: We have to obtain the numeric address from the bytes returned by <code>pack</code>.</p>

<pre><code>my $ptr = unpack( &#39;L!&#39;, $memptr );</code></pre>

<p>Obviously this assumes that it is possible to typecast a pointer to an unsigned long and vice versa, which frequently works but should not be taken as a universal law. - Now that we have this pointer the next question is: How can we put it to good use? We need a call to some C function where a pointer is expected. The read(2) system call comes to mind:</p>

<pre><code>ssize_t read(int fd, void *buf, size_t count);</code></pre>

<p>After reading <a href="perlfunc.html">perlfunc</a> explaining how to use <code>syscall</code> we can write this Perl function copying a file to standard output:</p>

<pre><code>require &#39;syscall.ph&#39;; # run h2ph to generate this file
sub cat($){
    my $path = shift();
    my $size = -s $path;
    my $memory = &quot;\x00&quot; x $size;  # allocate some memory
    my $ptr = unpack( &#39;L&#39;, pack( &#39;P&#39;, $memory ) );
    open( F, $path ) || die( &quot;$path: cannot open ($!)\n&quot; );
    my $fd = fileno(F);
    my $res = syscall( &amp;SYS_read, fileno(F), $ptr, $size );
    print $memory;
    close( F );
}</code></pre>

<p>This is neither a specimen of simplicity nor a paragon of portability but it illustrates the point: We are able to sneak behind the scenes and access Perl&#39;s otherwise well-guarded memory! (Important note: Perl&#39;s <code>syscall</code> does <i>not</i> require you to construct pointers in this roundabout way. You simply pass a string variable, and Perl forwards the address.)</p>

<p>How does <code>unpack</code> with <code>P</code> work? Imagine some pointer in the buffer about to be unpacked: If it isn&#39;t the null pointer (which will smartly produce the <code>undef</code> value) we have a start address - but then what? Perl has no way of knowing how long this &quot;fixed length string&quot; is, so it&#39;s up to you to specify the actual size as an explicit length after <code>P</code>.</p>

<pre><code>my $mem = &quot;abcdefghijklmn&quot;;
print unpack( &#39;P5&#39;, pack( &#39;P&#39;, $mem ) ); # prints &quot;abcde&quot;</code></pre>

<p>As a consequence, <code>pack</code> ignores any number or <code>*</code> after <code>P</code>.</p>

<p>Now that we have seen <code>P</code> at work, we might as well give <code>p</code> a whirl. Why do we need a second template code for packing pointers at all? The answer lies behind the simple fact that an <code>unpack</code> with <code>p</code> promises a null-terminated string starting at the address taken from the buffer, and that implies a length for the data item to be returned:</p>

<pre><code>my $buf = pack( &#39;p&#39;, &quot;abc\x00efhijklmn&quot; );
print unpack( &#39;p&#39;, $buf );    # prints &quot;abc&quot;</code></pre>

<p>Albeit this is apt to be confusing: As a consequence of the length being implied by the string&#39;s length, a number after pack code <code>p</code> is a repeat count, not a length as after <code>P</code>.</p>

<p>Using <code>pack(..., $x)</code> with <code>P</code> or <code>p</code> to get the address where <code>$x</code> is actually stored must be used with circumspection. Perl&#39;s internal machinery considers the relation between a variable and that address as its very own private matter and doesn&#39;t really care that we have obtained a copy. Therefore:</p>

<ul>

<li><p>Do not use <code>pack</code> with <code>p</code> or <code>P</code> to obtain the address of variable that&#39;s bound to go out of scope (and thereby freeing its memory) before you are done with using the memory at that address.</p>

</li>
<li><p>Be very careful with Perl operations that change the value of the variable. Appending something to the variable, for instance, might require reallocation of its storage, leaving you with a pointer into no-man&#39;s land.</p>

</li>
<li><p>Don&#39;t think that you can get the address of a Perl variable when it is stored as an integer or double number! <code>pack(&#39;P&#39;, $x)</code> will force the variable&#39;s internal representation to string, just as if you had written something like <code>$x .= &#39;&#39;</code>.</p>

</li>
</ul>

<p>It&#39;s safe, however, to P- or p-pack a string literal, because Perl simply allocates an anonymous variable.</p>

<h1 id="Pack-Recipes"><a class="permalink" href="perlpacktut.html#Pack-Recipes">#</a><a id="Pack"></a>Pack Recipes</h1>

<p>Here are a collection of (possibly) useful canned recipes for <code>pack</code> and <code>unpack</code>:</p>

<pre><code># Convert IP address for socket functions
pack( &quot;C4&quot;, split /\./, &quot;123.4.5.6&quot; ); 

# Count the bits in a chunk of memory (e.g. a select vector)
unpack( &#39;%32b*&#39;, $mask );

# Determine the endianness of your system
$is_little_endian = unpack( &#39;c&#39;, pack( &#39;s&#39;, 1 ) );
$is_big_endian = unpack( &#39;xc&#39;, pack( &#39;s&#39;, 1 ) );

# Determine the number of bits in a native integer
$bits = unpack( &#39;%32I!&#39;, ~0 );

# Prepare argument for the nanosleep system call
my $timespec = pack( &#39;L!L!&#39;, $secs, $nanosecs );</code></pre>

<p>For a simple memory dump we unpack some bytes into just as many pairs of hex digits, and use <code>map</code> to handle the traditional spacing - 16 bytes to a line:</p>

<pre><code>my $i;
print map( ++$i % 16 ? &quot;$_ &quot; : &quot;$_\n&quot;,
           unpack( &#39;H2&#39; x length( $mem ), $mem ) ),
      length( $mem ) % 16 ? &quot;\n&quot; : &#39;&#39;;</code></pre>

<h1 id="Funnies-Section"><a class="permalink" href="perlpacktut.html#Funnies-Section">#</a><a id="Funnies"></a>Funnies Section</h1>

<pre><code># Pulling digits out of nowhere...
print unpack( &#39;C&#39;, pack( &#39;x&#39; ) ),
      unpack( &#39;%B*&#39;, pack( &#39;A&#39; ) ),
      unpack( &#39;H&#39;, pack( &#39;A&#39; ) ),
      unpack( &#39;A&#39;, unpack( &#39;C&#39;, pack( &#39;A&#39; ) ) ), &quot;\n&quot;;

# One for the road ;-)
my $advice = pack( &#39;all u can in a van&#39; );</code></pre>

<h1 id="Authors"><a class="permalink" href="perlpacktut.html#Authors">#</a>Authors</h1>

<p>Simon Cozens and Wolfgang Laun.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
